package com.byzk.p2p.front.controller;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.vo.FundRecordUserVo;
import com.byzk.p2p.admin.score.dto.ScoreRecord;
import com.byzk.p2p.admin.score.service.ScoreRecordService;
import com.byzk.p2p.admin.system.dto.Good;
import com.byzk.p2p.admin.system.dto.GoodBuy;
import com.byzk.p2p.admin.system.dto.GoodType;
import com.byzk.p2p.admin.system.service.GoodBuyService;
import com.byzk.p2p.admin.system.service.GoodService;
import com.byzk.p2p.admin.system.service.GoodTypeService;
import com.byzk.p2p.admin.system.vo.GoodVo;
import com.byzk.p2p.admin.user.dto.CneeInfo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.CneeInfoServise;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * 积分商城
 * @author suker.zhou
 *
 */
@Controller
@Scope("prototype")
public class FrontGoodController extends BaseController implements Serializable{

	private static final long serialVersionUID = 1L;
	@Autowired
	private GoodService goodService;
	@Autowired
	private GoodTypeService goodTypeService;
	@Autowired
	private GoodBuyService goodBuyService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private ScoreRecordService scoreRecordService;
	@Autowired
	private CneeInfoServise cneeInfoServise;
	@Autowired
	private UserAuthService userAuthService;
	@Autowired
	private FundRecordService fundRecordService;
	
	/**
	 * 进人商品页面
	 * @param model
	 * @param good
	 * @return
	 */
	@RequestMapping(value="/good/list",method=RequestMethod.GET)
	public ModelAndView goodList(Model model,@ModelAttribute GoodVo good){
		User user = (User)session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		UserAccount account = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account = userAccountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account);
		model.addAttribute("auth", map);
		good.setIndex(1);
		good.setLimit(64);
		if(good.getSort()==null){
			good.setSort(-1);
		}
		PageInfo<GoodVo> pageInfo = goodService.listGood(good);
		List<GoodType> typeList = goodTypeService.listAll(new GoodType()).getPageList();
		List<GoodBuy> list = goodBuyService.new5GoodBuyList();
		if(user != null){
			CneeInfo info = new CneeInfo();
			info.setUserId(user.getId());
			List<CneeInfo> cnee = cneeInfoServise.list(info);//获取收获人信息
			model.addAttribute("cnee", cnee);
		}
		model.addAttribute("typeId", good.getTypeId());
		model.addAttribute("source", good.getAmount());
		model.addAttribute("goodBuy", list);
		model.addAttribute("pageInfo",pageInfo);
		model.addAttribute("typeList",typeList);
		return new ModelAndView("/front/good/list");
	}
	
	
	/**
	 * 商品购买
	 * @param good
	 * @throws Exception
	 */
	@RequestMapping(value ="/front/good/buy",method = RequestMethod.POST)
	public void buyGood(@ModelAttribute GoodBuy goodBuy) throws Exception{
		User user = (User)session.getAttribute("_user");
		try {
			user = userService.getById(user == null ?0:user.getId());
			if (user == null) {
				super.printJSON(new JsonMsg(1, "请先登录！"));
				return;
			}
			//购买数量问题
			if(goodBuy.getCount() == null || goodBuy.getCount().intValue() <1){
				super.printJSON(new JsonMsg(2, "商品数量不能小于1！"));
				return;
			}
			GoodVo good = goodService.detail(goodBuy.getGoodId());
			//用户剩余积分不足
			UserAccount account = userAccountService.getByUserId(user.getId());
			Integer goodScore = goodBuy.getCount()*good.getAmount();//兑换商品所需积分
			if (account == null || account.getScore() == null || account.getScore().intValue() < goodScore) {
				super.printJSON(new JsonMsg(2, "用户积分不足，兑换失败！"));
				return;
			}
			super.printJSON(new JsonMsg(-1, "确认购买！",goodBuy.getGoodId()));
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	/**
	 * 商品购买
	 * @param good
	 * @throws Exception
	 */
	@RequestMapping(value ="/front/good/confirm",method = RequestMethod.POST)
	public void confirm(@ModelAttribute GoodBuy goodBuy) throws Exception{
		User user = (User)session.getAttribute("_user");
		try {
			user = userService.getById(user == null ?0:user.getId());
			if (user == null) {
				super.printJSON(new JsonMsg(1, "请先登录！"));
				return;
			}
			CneeInfo info = cneeInfoServise.selectById(goodBuy.getCneeId());
			GoodVo good = goodService.detail(goodBuy.getGoodId());
			//用户剩余积分不足
			UserAccount account = userAccountService.getByUserId(user.getId());
			//判断用户等级,对相应用户做兑换积分优惠
			Integer goodScore = 0 ; 
			if(account.getLevel() == 2){//vip会员
				goodScore = (int) (good.getAmount()*0.98);//兑换商品所需积分
			}else if(account.getLevel() == 3){//金牌会员
				goodScore = (int) (good.getAmount()*0.95);
			}else if(account.getLevel() == 4){//白金会员
				goodScore = (int) (good.getAmount()*0.91);
			}else if(account.getLevel() == 5){//钻石会员
				goodScore = (int) (good.getAmount()*0.85);
			}else if(account.getLevel() == 6){//金钻会员
				goodScore = (int) (good.getAmount()*0.77);
			}else{
				goodScore =  good.getAmount();
			}
			if (account == null || account.getScore() == null || account.getScore().intValue() < goodScore) {
				super.printJSON(new JsonMsg(2, "用户积分不足，兑换失败！"));
				return;
			}
			
			//记录兑换记录
			goodBuy.setUserId(user.getId());
			goodBuy.setScore(goodScore);
			goodBuy.setBuyTime(new Date());
			goodBuy.setStatus(0);
			goodBuy.setUsername(info.getName());
			goodBuy.setPhone(info.getPhone());
			goodBuy.setAddress(info.getAddress());
			goodBuy.setCount(1);
			Integer i = goodBuyService.saveOrUpdate(goodBuy);
			if (i>0) {
				//商品数量减少
				good.setSum(good.getSum()-1);
				goodService.saveOrUpdate1(good);
				//减少用户积分
				account.setScore(account.getScore()-goodScore);
				userAccountService.saveOrUpdate(account);
				//记录积分流水
				ScoreRecord scoreRecord = new ScoreRecord();
				scoreRecord.setUserId(user.getId());
				scoreRecord.setOptType("out");
				scoreRecord.setAmount(goodScore);
				scoreRecord.setWay("积分兑换");
				scoreRecord.setCreateTime(new Date());
				scoreRecord.setTerminal("PC");
				scoreRecord.setObjectId(goodBuy.getId());
				scoreRecordService.saveScoreRecord(scoreRecord);
			}
			if (i>0) {
				printJSON(new JsonMsg(-1, "兑换成功！"));
			}else{
				printJSON(new JsonMsg(1, "兑换失败！"));
			} 
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	@RequestMapping(value="/good/list",method=RequestMethod.POST)
	public void listGood(Model model,@ModelAttribute GoodVo good) throws Exception{
		User user = (User)session.getAttribute("_user");
		user = userService.getById(user == null ?0:user.getId());
		good.setIndex(1);
		good.setLimit(16);
		PageInfo<GoodVo> pageInfo = goodService.listGood(good);
		if(!pageInfo.getPageList().isEmpty()){
			printJSON(new JsonMsg(-1, "查询成功！",pageInfo));
			return ;
		}
		printJSON(new JsonMsg(1, "暂无数据！",pageInfo));
	}
	
	@RequestMapping("/score/draw")
	public ModelAndView draw(Model model){
		List<FundRecordUserVo> drawList = fundRecordService.getDrawRecordList();
		model.addAttribute("drawList", drawList);
		return new ModelAndView("/front/good/draw");
	}
}
